/**
 * Created by zhangqi on 2015/7/10.
 * 一些工具函数
 */

define(function(require,exports,module){
    var Tools = {
        /**
         * 浏览器缓存工具利用webStorage(sessionStorage、localStorage)
         * */
        Cache:{
            /**
             * 获取缓存
             * @key 缓存的键
             * @type 缓存的类型 local:localStorage,session:sessionStorage，默认使用localStorage
             * */
            getCache:function(key,type){
                type = type || "local";
                var oVal = null;
                //如果是localStorage
                if(type == "local"){
                    var sVal = localStorage.getItem(key);
                    if(sVal && (sVal.indexOf("{") != -1 || (sVal.indexOf("[") != -1 && Object.prototype.toString.call(JSON.parse(sVal)) === "[object Array]") )){
                        oVal = JSON.parse(sVal);
                    }
                }else if(type == "session"){  //如果是sessionStorage
                    var sVal = sessionStorage.getItem(key);
                    if(sVal && sVal.indexOf("{") != -1){
                        oVal = JSON.parse(sVal);
                    }
                }
                return oVal;
            },
            /**
             * 设置缓存
             * @key 缓存的键
             * @type 缓存的类型：localStorage、sessionStorage，默认使用localStorage
             * */
            setCache:function(key,value,type){
                type = type || "local";
                if(!value){return;}
                //如果是localStorage
                if(type == "local"){
                    if(typeof value == "string"){
                        localStorage.setItem(key,value);
                    }
                    if(typeof value == "object"){
                        localStorage.setItem(key,JSON.stringify(value));
                    }
                }else if(type == "session"){  //如果是sessionStorage
                    if(typeof value == "string"){
                        sessionStorage.setItem(key,value);
                    }
                    if(typeof value == "object"){
                        sessionStorage.setItem(key,JSON.stringify(value));
                    }
                }
            }

        },
        /**
         * 加密结果工具
         * */
        LockerStr:{
            /**
             * 加密
             * @str 字符串
             * @secretKey key
             * */
            encrypt:function(str, secretKey) {
                if (secretKey == null || secretKey.length <= 0) {
                    alert("Please enter a key with which to encrypt the message.");
                    return null;
                }
                var prand = "";
                for (var i = 0; i < secretKey.length; i++) {
                    prand += secretKey.charCodeAt(i).toString();
                }
                var sPos = Math.floor(prand.length / 5);
                var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) + prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
                var incr = Math.ceil(secretKey.length / 2);
                var modu = Math.pow(2, 31) - 1;
                if (mult < 2) {
                    alert("Algorithm cannot find a suitable hash. Please choose a different key. \nPossible considerations are to choose a more complex or longer key.");
                    return null;
                }
                var salt = Math.round(Math.random() * 1000000000) % 100000000;
                prand += salt;
                while (prand.length > 10) {
                    prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
                }
                prand = (mult * prand + incr) % modu;
                var enc_chr = "";
                var enc_str = "";
                for (var i = 0; i < str.length; i++) {
                    enc_chr = parseInt(str.charCodeAt(i) ^ Math.floor((prand / modu) * 255));
                    if (enc_chr < 16) {
                        enc_str += "0" + enc_chr.toString(16);
                    } else enc_str += enc_chr.toString(16);
                    prand = (mult * prand + incr) % modu;
                }
                salt = salt.toString(16);
                while (salt.length < 8) salt = "0" + salt;
                enc_str += salt;
                return enc_str;
            },
            /**
             * 加密
             * @str 字符串
             * @secretKey key
             * */
            decrypt:function(str, secretKey) {
                if (str == null || str.length < 8) {
                    alert("A salt value could not be extracted from the encrypted message because it's length is too short. The message cannot be decrypted.");
                    return;
                }
                if (secretKey == null || secretKey.length <= 0) {
                    alert("Please enter a password with which to decrypt the message.");
                    return;
                }
                var prand = "";
                for (var i = 0; i < secretKey.length; i++) {
                    prand += secretKey.charCodeAt(i).toString();
                }
                var sPos = Math.floor(prand.length / 5);
                var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) + prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
                var incr = Math.round(secretKey.length / 2);
                var modu = Math.pow(2, 31) - 1;
                var salt = parseInt(str.substring(str.length - 8, str.length), 16);
                str = str.substring(0, str.length - 8);
                prand += salt;
                while (prand.length > 10) {
                    prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
                }
                prand = (mult * prand + incr) % modu;
                var enc_chr = "";
                var enc_str = "";
                for (var i = 0; i < str.length; i += 2) {
                    enc_chr = parseInt(parseInt(str.substring(i, i + 2), 16) ^ Math.floor((prand / modu) * 255));
                    enc_str += String.fromCharCode(enc_chr);
                    prand = (mult * prand + incr) % modu;
                }
                return enc_str;
            }
         },
        /**
         * 对日期进行格式化，
         * @param date 要格式化的日期
         * @param format 进行格式化的模式字符串
         *     支持的模式字母有：
         *     y:年,
         *     M:年中的月份(1-12),
         *     d:月份中的天(1-31),
         *     h:小时(0-23),
         *     m:分(0-59),
         *     s:秒(0-59),
         *     S:毫秒(0-999),
         *     q:季度(1-4)
         * @return String
         * @demo: dateFormat(newDate(),'yyyy-MM-dd hh:mm:ss')
         */
        dateFormat:function(date, format){
            if(format ===undefined){
                format = date;
                date =new Date();
            }
            var map ={
                "M": date.getMonth()+1,//月份
                "d": date.getDate(),//日
                "h": date.getHours(),//小时
                "m": date.getMinutes(),//分
                "s": date.getSeconds(),//秒
                "q":Math.floor((date.getMonth()+3)/3),//季度
                "S": date.getMilliseconds()//毫秒
            };
            format = format.replace(/([yMdhmsqS])+/g,function(all, t){
                var v = map[t];
                if(v !==undefined){
                    if(all.length >1){
                        v ='0'+ v;
                        v = v.substr(v.length-2);
                    }
                    return v;
                }else if(t ==='y'){
                    return(date.getFullYear()+'').substr(4- all.length);
                }
                return all;
            });
            return format;
        },
        /**
         * 获取Html转义字符
         * */
        htmlEncode:function(html){
            return document.createElement('a').appendChild(document.createTextNode(html)).parentNode.innerHTML;
        },
        /**
         * 获取Html
         * */
        htmlDecode:function(html){
            var a = document.createElement( 'a' ); a.innerHTML = html;
            return a.textContent;
        },
        /**
         *时间轴数据转换
        **/
        data2time:function(data){ 
            var that=this,
                len=data.length,
                d=data,
                newD={},
                c=[];
                for(var i=0;i<len;i++){ 
                    var pnewdate=d[i].createDate.replace(/-/g,'/');
                    var cn=new Date(pnewdate);
                    var a=this.dateFormat(cn,'yyyy-MM');
                        d[i].ym=this.dateFormat(cn,'yyyy年MM月');
                        d[i].m=this.dateFormat(cn,'MM月');
                        d[i].d=this.dateFormat(cn,'dd日');
                        if(typeof newD[a]=="undefined"){ 
                            newD[a]=[];
                        }
                        newD[a].push(d[i]);
                };

            return newD;
        },

	    /**
         * 重新提供四舍五入方法，因为原生的toFixed有问题，如12.225.toFixed(2)，得到结果为12.22，希望值为12.23
         * @param number  需要处理的数字
         * @param fractionDigits  保留小数点后几位
         * @returns {string}
	     */
        toFixed: function(number, fractionDigits){
            fractionDigits = fractionDigits || 2; //默认保留小数点后两位
            var times = Math.pow(10, fractionDigits);
            //此处需要再用toFixed处理一下特殊情况，如168.096保留小数点两位，结果应该是168.10
            return (Math.round(number * times) / times).toFixed(fractionDigits);
        },

        /**
         * 价格格式化
         * @param number
         */
        moneyFormat: function(number, unitClass){
            number = Number(number);
            //判断传入的是否是数字。处理特殊情况，如number为null,undefined,非数字的字符串,boolean,
            if(!$.isNumeric(number)){
                return '';
            }
            var roundNumber = parseInt(number); //取整
            var length = roundNumber.toString().length;
            var result;
            if(length <= 3){
                result =  this.toFixed(number, 2) + '元';
            } else if(length == 4){
                number = String(this.toFixed(number, 2));
                var re = /(-?\d+)(\d{3})/;
                while(re.test(number)) {
                    number = number.replace(re,"$1,$2");
                }
                result = number + '元';
            } else if(length <= 6){
                result = this.toFixed(number / 10000, 2) + '万元';
            } else if(length == 7){
                result = this.toFixed(number / 1000000, 2) + '百万';
            } else {
                result = this.toFixed(number / 10000000, 2) + '千万';
            }
            if(unitClass){
                result = result.replace(/([^0-9.]+)/, '<span class="money_unit">$1</span>' );
            }
            return result;
        },

        formatPrice : function(str) {
            var str = this.toFixed(Number(str.toString()), 2);
            var newStr = "";
            var count = 0;
            for (var i = str.indexOf(".") - 1; i >= 0; i--) {
                if (count % 3 == 0 && count != 0) {
                    newStr = str.charAt(i) + "," + newStr;
                } else {
                    newStr = str.charAt(i) + newStr; //逐个字符相接起来
                }
                count++;
            }
            str = newStr + (str + "00").substr((str + "00").indexOf("."), 3);
            return str;
        },

        /**
         * 判断页面是否可编辑
         */
        isPageEditable: function(empId){
            if(isEdit == 'true'){
                return 'true';
            }
            if(empId && empId == homeUser.empId){
                return 'true'
            }
            var $soleFrame = $(parent.document).find('.soleFrame');
            if($soleFrame.length > 0){
                var empId = $soleFrame.attr('data-empid');
                return empId == homeUser.empId ? 'true': 'false';
            }
            return 'false';
        },

        /**
         * 判断是否已加载模块的html模板文件，否，则加载后执行回调函数，是，则立即执行回调函数
         * @param moduleName 模块名称
         * @param callback   回调函数
         */
        getTpl : function(moduleName, callback){
            if($("#base_templates").find(">script."+moduleName+"_tpl").length){
                typeof callback == "function" && callback();
            }else{
                $.get(window.localhost+"/static/html/"+moduleName+".html?v=" + Date.now(),function(html){
                    $("#base_templates").append(html);
                    typeof callback == "function" && callback();
                });
            }
        },

	    /**
         * 将JSON对象对象转换为请求参数
         * @param object
         */
        jsonToQueryString: function(jsObj){
            var tmp='',
                i=0;
            for(var x in jsObj){
                i++;
                if(i == 1){
                    tmp = tmp + x + '=' + jsObj[x];
                }else{
                    tmp = tmp + '&' + x + '=' + jsObj[x];
                }
            }
            return tmp;
        },

        /**
         * 在jQuery中添加，子元素滚动，父元素不滚动的方法
         */
        addScrollPlugin: function(){
            if($.fn.scrollToLoadMore){
                return;
            }
            $.fn.scrollToLoadMore = function(options) {
                return $(this).each(function() {
                    var eventType = 'mousewheel';
                    // 火狐是DOMMouseScroll事件
                    if (window.MouseScrollEvent) {
                        eventType = 'DOMMouseScroll';
                    }
                    $(this).on(eventType, function(event) {
                        // 一些数据
                        var scrollTop = this.scrollTop,   //滚动条位置
                            scrollHeight = this.scrollHeight,
                            height = this.clientHeight;  //可视区域的高度。

                        var delta = (event.originalEvent.wheelDelta) ? event.originalEvent.wheelDelta : -(event.originalEvent.detail || 0);
                        //禁止向下滚动
                        if(delta > 0 && scrollTop <= 0){
                            event.preventDefault();
                        }
                        if (delta < 0 && scrollHeight - height - scrollTop - 30 <= -1 * delta) {
                            // IE浏览器下滚动会跨越边界直接影响父级滚动，因此，临界时候手动边界滚动定位
                            this.scrollTop = delta > 0? 0: scrollHeight;

                            //加载更多数据
                            if(options.loadMore && $.isFunction(options.loadMore)){
                                options.loadMore.apply(options, [$(this)]);
                            }

                            event.preventDefault();
                        }
                    });
                });
            };
        },

        addInputMoneyFormat: function(){
            var t = this;
            if($.fn.moneyFormat){
                return;
            }
            $.fn.moneyFormat = function(options){
                return $(this).each(function(){
                    var $this = $(this);
                    //只能输入数字和小数点
                    $this.on('keydown', function(event){
                        var keyCode = event.keyCode;
                        if ((keyCode >= 48 && keyCode <= 57)  //大键盘的数字
                            || (keyCode >= 96 && keyCode <= 105)  //小键盘的数字
                            || keyCode == 110  //大键盘 小数点
                            || keyCode == 190  //小键盘 小数点
                            || keyCode == 8    //删除键
                            || (keyCode >= 37 && keyCode <= 40)  //方向键
                        ){
                            return true;
                        }
                        return false;
                    });
                    $this.on('focus', function(){
                        var val = t.getNumber($this.val())
                        //如果为0，则置为空
                        $this.val(val === 0 ? '': val);
                    });
                    $this.on('blur', function(){
                        $this.val(t.amountFormat($this.val()))
                    });
                })
            }
        },

        addInputNumber: function(){
            var t = this;
            if($.fn.numberType){
                return;
            }
            //输入框只能输入数字
            $.fn.numberType = function(options){
                return $(this).each(function(){
                    var $this = $(this);
                    var isInt = options.isInt || false;
                    //只能输入数字和小数点
                    $this.on('keydown', function(event){
                        var keyCode = event.keyCode;
                        if ((keyCode >= 48 && keyCode <= 57)  //大键盘的数字
                            || (keyCode >= 96 && keyCode <= 105)  //小键盘的数字
                            || keyCode == 8    //删除键
                            || (keyCode >= 37 && keyCode <= 40)  //方向键
                        ){
                            return true;
                        }
                        //如果为正整数，则不能输入小数点
                        if(!isInt && (keyCode == 110 || keyCode == 190)){  //小键盘 小数点  //大键盘 小数点
                            return true;
                        }
                        return false;
                    });
                    $this.on('focus', function(){
                        var val = $this.val();
                        //如果为0，则置为空
                        $this.val(val > 0 ? val: '');
                    });
                    $this.on('blur', function(){
                        var val = $this.val();
                        $this.val(val != '' && val > 0  ? val: '0');
                    });
                })
            }
        },

	    /**
         * 还原千分位显示的值为纯数字
         * @param numberStr
         * @returns {number}
         */
        getNumber: function(numberStr){
            var notNumber = /[^0-9\.]/g;
            return Number(numberStr.replace(notNumber, ''));
        },

        /**
         * 金额格式化，千位分隔符
         **/
        amountFormat: function(number){
            if(/[^0-9\.]/.test(number)){
                console.log('无效数字')
                return "";
            }
            number = number + '';  //如果为数字类型，则转换为string类型
            number = number.replace(/^(\d*)$/,"$1.");
            number = (number + "00").replace(/(\d*\.\d\d)\d*/,"$1");
            number = number.replace(".",",");
            var re=/(\d)(\d{3},)/;
            while(re.test(number))
                number = number.replace(re,"$1,$2");
            number = number.replace(/,(\d\d)$/,".$1");
            return "￥" + number.replace(/^\./,"0.")
        },

        //获取当前页面最大的z-index
        getMaxZIndex: function(){
            var time = Date.now();
            var maxZ = Math.max.apply(null, $.map($('body > div'), function (e, n) {
                var $e = $(e);
                var position = $e.css('position');
                if (position == 'absolute' || position == 'fixed'){
                    return parseInt($e.css('z-index')) || 1;
                }
            }));
            return maxZ;
        },

        monthBeginning: function (date) {
            date.setDate(1);
            return date;
        },

        monthEnding: function (date) {
	        date.setMonth(date.getMonth() + 1);
	        date.setDate(0);
	        return date;
        },

        /**
         * 获取省市区信息
         * @param provinceId
         * @param cityId
         * @param areaId
         * @returns {*}
         */
        getProvinceInfo: function (provinceId, cityId, areaId) {
            var info = '';
            var provinceName = $(provinceId + ' .ui-val').html();
            if(!provinceName || provinceName == '省份'){
                return ''
            }
            info += provinceName;
            var cityName = $(cityId + ' .ui-val').html();
            if(!cityName || cityName == '地级市'){
                return info;
            }
            info += (cityName == '市辖区' || cityName == '县') ? '': cityName;
            var areaName = $(areaId + ' .ui-val').html();
            if(!areaName || areaName == '市、县级市'){
                return info;
            }
            return info + areaName;
        }

    };

    Tools.addInputMoneyFormat();
    Tools.addInputNumber();


    module.exports = Tools;
});
